package org.chromium.latency.walt;

import android.view.Choreographer;

public class FpsCounter implements Choreographer.FrameCallback {

    interface FpsNotify{
        void Notify(int fps, float frameLatencyMs);
    }

    private FpsNotify callback;

    public FpsCounter SetNotify(FpsNotify cb){
        callback = cb;
        return this;
    }

    private static FpsCounter _instance = null;
    public static FpsCounter getInstance(){
        if(_instance == null){
            _instance = new FpsCounter();
        }
        return _instance;
    }

    private int intervalMs = 1000;
    private float totalFrameTimeMs = 0;
    private int totalFrameCounts = 0;
    private float lastFrameTimeNanos = 0;
    public int GetFrameFrequency(){
        return Math.round(totalFrameCounts / totalFrameTimeMs * 1000);
    }

    public float GetFrameLatencyMs(){
        return totalFrameTimeMs / totalFrameCounts;
    }

    @Override
    public void doFrame(long frameTimeNanos) {
        if(lastFrameTimeNanos != 0){
            totalFrameCounts ++;
            totalFrameTimeMs += (frameTimeNanos - lastFrameTimeNanos) / 1000000.f;
            if(totalFrameTimeMs >= intervalMs){
                if(callback != null){
                    callback.Notify(GetFrameFrequency(), GetFrameLatencyMs());
                }
                totalFrameCounts = 0;
                totalFrameTimeMs = 0;
            }
        }
        lastFrameTimeNanos = frameTimeNanos;
        Choreographer.getInstance().postFrameCallback(this);
    }
}
